/*
 * Created on Aug 4, 2006
 *
 */
package com.inibb.app.sftp;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.inibb.app.sftp.exception.SFTPConnectionPoolException;
import com.inibb.app.sftp.exception.SFTPIOException;




/**
 * @author PCCW
 *
 */
public class SFTPConnectionPoolMap {
	private static final Logger LOG = LoggerFactory.getLogger(PooledSFTPConnection.class);

	private HashMap map = new HashMap();
	
	/**
	 * To obtain a SFTPConnection instance (non-exclusive, with auto-reconnect).
	 * @param key - the section code of TSS to be connecting
	 * @return
	 * @throws SFTPConnectionPoolException
	 */
	public SFTPConnection getConnection(String key) 
		throws SFTPConnectionPoolException
	{
		SFTPConnectionPool pool = (SFTPConnectionPool)map.get(key);
		if (pool==null) {
			throw new SFTPConnectionPoolException(SFTPConnectionPoolException.CODE_RUNTIME,"No SFTPConnection for ["+key+"]");
		} else {
			return pool.getConnection();
		}
	}

	/**
	 * To obtain (create) an exclusive SFTPConnection instance for given section code (with auto-reconnect).
	 * Please disconnect the connection after use.
	 * @param key - the section code of TSS to be connecting
	 * @return
	 * @throws SFTPConnectionPoolException
	 * @throws SFTPIOException
	 */
	public SFTPConnection getExclusiveConnection(String key) 
		throws SFTPConnectionPoolException,SFTPIOException
	{
		SFTPConnectionPool pool = (SFTPConnectionPool)map.get(key);
		if (pool==null) {
			throw new SFTPConnectionPoolException(SFTPConnectionPoolException.CODE_RUNTIME,"No SFTPConnection for ["+key+"]");
		} else {
			return pool.getExclusiveConnection();
		}
	}
	
	SFTPConnectionPool putPool(Object key, SFTPConnectionPool pool) {
		SFTPConnectionPool o =  (SFTPConnectionPool)map.put(key,pool);
		return o;		
	}
	
	SFTPConnectionPool getPool(Object key) {
		return (SFTPConnectionPool) map.get(key);
	}
	
	SFTPConnectionPool removePool(Object key) {
		SFTPConnectionPool o = (SFTPConnectionPool) map.remove(key);
		return o;
	}
	
	
	void disconnectAll() {
		SFTPConnectionPool[] pools = (SFTPConnectionPool[])map.values().toArray(new SFTPConnectionPool[0]);
		for (int i=0;i<pools.length;i++) {
			LOG.debug("Disconnecting connections to ["+pools[i].getName()+"]");
			pools[i].disconnectAll();
		}
	}
	
	synchronized void destroy() {
		disconnectAll();
		map.clear();
	}
	
	public String[] getDefinedPools() {
		return (String[]) map.keySet().toArray(new String[0]);
		
	}
	
}
